package com.bto.solar.work.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.dao.IOrderOperationLogService;
import com.bto.solar.work.dto.ApprovalReq;
import com.bto.solar.work.entity.OrderOperationLog;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.ServletUtils;
import com.bto.solar.work.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 王小波
 * @description:
 * @date 2023/8/21 14:49
 */
@Service
@Slf4j
public class BtoOperateLogService {
    @Autowired
    private IOrderOperationLogService orderOperationLogService;
    @Autowired
    private BtoUserService btoUserService;

    private final ThreadLocal<ApprovalReq> threadLocalApprovalReq = new ThreadLocal<>();

    private final ThreadLocal<JSONObject> threadLocalOperatInfo = new ThreadLocal<>();

    public void setApprovalInfo(ApprovalReq approvalInfo) {
        threadLocalApprovalReq.set(approvalInfo);
    }

    public void setOperatInfo(JSONObject operatInfo) {
        threadLocalOperatInfo.set(operatInfo);
    }

    public void saveOrderOperateLog(String orderId, String stageId, String taskId, String stateId, String optType, Object data) {
        saveOrderOperateLog(orderId, stageId, taskId, stateId, optType, data, null);
    }

    public void saveOrderOperateLog(String orderId, String stageId, String taskId, String stateId, String optType, Object data, String remark) {
        OrderOperationLog orderOperationLog = new OrderOperationLog();
        orderOperationLog.setOrderId(orderId);
        orderOperationLog.setStageId(stageId);
        orderOperationLog.setTaskId(taskId);
        orderOperationLog.setStateId(stateId);
        orderOperationLog.setRemark(remark);
        orderOperationLog.setOperatInfo(JSON.toJSONString(data));
        orderOperationLog.setType(optType);

        if (NullUtils.isNotNull(threadLocalOperatInfo.get())) {
            orderOperationLog.setOperatInfo(JSON.toJSONString(threadLocalOperatInfo.get()));
        }

        if (NullUtils.isNotNull(threadLocalApprovalReq.get())) {
            if (NullUtils.isNotNull(threadLocalApprovalReq.get().getApprover())) {
                orderOperationLog.setOperatUser(threadLocalApprovalReq.get().getApprover());
            }
        } else {
            try {
                Integer userId = ServletUtils.getHeaderToInt(Constants.HEADER_USER_ID);
                if (NullUtils.isNotNull(userId)) {
                    orderOperationLog.setOperatUser(btoUserService.getCurrentUser().getUserId());
                }
            } catch (Exception e) {
                orderOperationLog.setOperatUser(null);
            }

        }

        //审核通过、拒绝的时候，把审核的数据保存一份
        if (StringUtils.isNotEmpty(stateId) && (stateId.startsWith("APPROVAL") || stateId.startsWith(BizTaskStateEnum.TERMINATE.getStateId()))) {
            OrderOperationLog one = orderOperationLogService.lambdaQuery()
                    .select(OrderOperationLog::getOperatInfo)
                    .eq(OrderOperationLog::getOrderId, orderId)
                    .eq(StringUtils.isNotEmpty(stageId), OrderOperationLog::getStageId, stageId)
                    .eq(StringUtils.isNotEmpty(taskId), OrderOperationLog::getTaskId, taskId)
                    .eq(StringUtils.isNotEmpty(stateId), OrderOperationLog::getStateId, BizTaskStateEnum.WAITING_FILLED.getStateId())
                    .orderByDesc(OrderOperationLog::getCreateTime)
                    .last("LIMIT 1").one();
            if (NullUtils.isNotNull(one)) {
                orderOperationLog.setOperatInfo(one.getOperatInfo());
                log.info("threadLocalApprovalReq {}", threadLocalApprovalReq.get());
                if (NullUtils.isNotNull(threadLocalApprovalReq.get())) {
                    orderOperationLog.setApprovalInfo(JSON.toJSONString(threadLocalApprovalReq.get()));
                    threadLocalApprovalReq.remove();
                }
            }
        }
        orderOperationLogService.save(orderOperationLog);
    }


}
